package com.sita.cfmoto.interact.activity;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.maps.model.LatLng;
import com.edmodo.cropper.CropImageView;
import com.google.gson.Gson;
import com.sita.cfmoto.R;
import com.sita.cfmoto.event.ReleaseActiveEvent;
import com.sita.cfmoto.rest.RestClient;
import com.sita.cfmoto.rest.model.ReleaseActiveParams;
import com.sita.cfmoto.rest.model.RestResponse;
import com.sita.cfmoto.support.Constants;
import com.sita.cfmoto.utils.BitmapUtils;
import com.sita.cfmoto.utils.JsonUtils;
import com.sita.cfmoto.utils.PersistUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.trinea.android.common.util.ToastUtils;
import de.greenrobot.event.EventBus;
import pl.aprilapps.easyphotopicker.DefaultCallback;
import pl.aprilapps.easyphotopicker.EasyImage;
import pl.tajchert.nammu.Nammu;
import pl.tajchert.nammu.PermissionCallback;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;

public class ReleaseActiveActivity extends AppCompatActivity {

    private final int FLAG_DATE_PICKUP_APPLICATION_START = 0;
    private final int FLAG_DATE_PICKUP_APPLICATION_END = 1;
    private final int FLAG_DATE_PICKUP_ACTIVE_START = 2;
    private final int FLAG_DATE_PICKUP_ACTIVE_END = 3;

    private final int REQUEST_CODE_START = 1;
    private final int REQUEST_CODE_END = 2;

    private boolean mActivePicSet = false;
    private LatLng mStartLoc;
    private String mStartLocString;
    private LatLng mEndLoc;
    private String mEndLocString;

    private Date mDateApplicationStart, mDateApplicationEnd, mDateActiveStart, mDateActiveEnd;

    @Bind(R.id.pop_parent)
    LinearLayout popParent;
    @Bind(R.id.active_pic)
    ImageView mActivePic;
    @Bind(R.id.active_sign_start)
    TextView signStart;
    @Bind(R.id.active_sign_end)
    TextView signEnd;
    @Bind(R.id.active_time_start)
    TextView timeStart;
    @Bind(R.id.active_time_end)
    TextView timeEnd;
    @Bind(R.id.active_start)
    TextView activeStartAddress;
    @Bind(R.id.active_end)
    TextView activeEndAddress;
    @Bind(R.id.comment_content)
    EditText activeContent;
    @Bind(R.id.active_name)
    EditText activeName;
    @Bind(R.id.active_max_member)
    EditText activeMemberMax;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_active);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.cancel)
    void onClickBack() {
        finish();
    }

    @OnClick(R.id.finish)
    void onClickFinish() {
        releaseActive();
    }

    @OnClick(R.id.active_start)
    void onClickActiveStart() {
        startActivityForResult(ReleaseActiveMapActivity.newIntent(this, mStartLoc, mStartLocString),
                REQUEST_CODE_START);
    }

    @OnClick(R.id.active_end)
    void onClickActiveEnd() {
        startActivityForResult(ReleaseActiveMapActivity.newIntent(this, mEndLoc, mEndLocString),
                REQUEST_CODE_END);
    }

    @OnClick(R.id.active_sign_start)
    void onClickSignStart() {
        showDataPickerDialog(signStart, FLAG_DATE_PICKUP_APPLICATION_START);
    }

    @OnClick(R.id.active_sign_end)
    void onClickSignEnd() {
        showDataPickerDialog(signEnd, FLAG_DATE_PICKUP_APPLICATION_END);
    }

    @OnClick(R.id.active_time_start)
    void onClickTimeStart() {
        showDataPickerDialog(timeStart, FLAG_DATE_PICKUP_ACTIVE_START);
    }

    @OnClick(R.id.active_time_end)
    void onClickTimeEnd() {
        showDataPickerDialog(timeEnd, FLAG_DATE_PICKUP_ACTIVE_END);
    }

    @OnClick(R.id.active_pic)
    void onClickActivePic() {
        openPhotoPopup();
    }

    private void openPhotoPopup() {
        PopupWindow pop = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.item_dynamic_pic_pop, null);
        LinearLayout popupLayout = (LinearLayout) view.findViewById(R.id.popup_layout);
        pop.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        pop.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setOutsideTouchable(true);
        pop.setContentView(view);
        pop.showAtLocation(popParent, Gravity.BOTTOM, 0, 0);
        pop.update();

        RelativeLayout itemLayout = (RelativeLayout) view.findViewById(R.id.item_layout);
        Button btCam = (Button) view
                .findViewById(R.id.item_popupwindows_camera);
        Button btPhoto = (Button) view
                .findViewById(R.id.item_popupwindows_Photo);
        Button btCancel = (Button) view
                .findViewById(R.id.item_popupwindows_cancel);
        itemLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        btCam.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // take photo
                clickTakePhoto();
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        btPhoto.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                clickPickFromGallery();
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
        btCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pop.dismiss();
                popupLayout.clearAnimation();
            }
        });
    }

    protected void clickTakePhoto() {
        /**Permission check only required if saving pictures to root of sdcard*/
        int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            EasyImage.openCamera(this, 0);
            getIntent().putExtra(Constants.BUNDLE_APP_STATE, Constants.AppState.IN_CAMERA_PHOTO.name());
        } else {
            Nammu.askForPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE, new PermissionCallback() {
                @Override
                public void permissionGranted() {
                    EasyImage.openCamera(ReleaseActiveActivity.this, 0);
                    getIntent().putExtra(Constants.BUNDLE_APP_STATE, Constants.AppState.IN_CAMERA_PHOTO.name());
                }

                @Override
                public void permissionRefused() {

                }
            });
        }
    }

    protected void clickPickFromGallery() {
        /** Some devices such as Samsungs which have their own gallery app require write permission. Testing is advised! */
        getIntent().putExtra(Constants.BUNDLE_APP_STATE, Constants.AppState.IN_CAMERA_PHOTO.name());
        EasyImage.openGallery(this, 1);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_START && resultCode == RESULT_OK) {
            LatLng latLng = data.getParcelableExtra("LatLon");
            mStartLoc = latLng;
            mStartLocString = data.getStringExtra("Address");
            activeStartAddress.setText(mStartLocString);

        } else if (requestCode == REQUEST_CODE_END && resultCode == RESULT_OK) {
            LatLng latLng = data.getParcelableExtra("LatLon");
            mEndLoc = latLng;
            mEndLocString = data.getStringExtra("Address");
            activeEndAddress.setText(mEndLocString);
        }
        EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
            @Override
            public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
                //Some error handling
            }

            @Override
            public void onImagePicked(File imageFile, EasyImage.ImageSource source, int type) {
                //Handle the image
//                Picasso.with(GlobalContext.getGlobalContext())
//                        .load(imageFile).centerInside()
//                        .fit()
//                        .into(mActivePic);
//
//                mActivePic.setTag(imageFile.getAbsolutePath());
                showCropWindow(imageFile);
            }

            @Override
            public void onCanceled(EasyImage.ImageSource source, int type) {
                //Cancel handling, you might wanna remove taken photo if it was canceled
                if (source == EasyImage.ImageSource.CAMERA) {
                    File photoFile = EasyImage.lastlyTakenButCanceledPhoto(ReleaseActiveActivity.this);
                    if (photoFile != null) photoFile.delete();
                }
            }
        });
    }

    private void showDataPickerDialog(TextView tv, int dateType) {
        Calendar mCalendar = Calendar.getInstance(Locale.CHINA);
        Date mDate = new Date();
        mCalendar.setTime(mDate);

        int year = mCalendar.get(Calendar.YEAR);
        int month = mCalendar.get(Calendar.MONTH);
        int day = mCalendar.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog datePickerDialog = new DatePickerDialog(ReleaseActiveActivity.this, android.R.style.Theme_Holo_Light_Dialog, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                if (tv != null) {
                    int hour;
                    int minute;
                    int second;
                    if (dateType == FLAG_DATE_PICKUP_ACTIVE_START || dateType == FLAG_DATE_PICKUP_APPLICATION_START) {
                        hour = 0;
                        minute = 0;
                        second = 0;
                    } else {
                        hour = 23;
                        minute = 59;
                        second = 59;
                    }
                    mCalendar.set(Calendar.YEAR, year);
                    mCalendar.set(Calendar.MONTH, monthOfYear);
                    mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    mCalendar.set(Calendar.HOUR_OF_DAY, hour);
                    mCalendar.set(Calendar.MINUTE, minute);
                    mCalendar.set(Calendar.SECOND, second);

                    switch (dateType) {
                        case FLAG_DATE_PICKUP_APPLICATION_START:
                            if (mDateApplicationEnd != null && mCalendar.getTime().after(mDateApplicationEnd)) {
                                ToastUtils.show(getApplicationContext(), getString(R.string.active_release_date_error));
                                return;
                            }
                            mDateApplicationStart = mCalendar.getTime();

                            break;
                        case FLAG_DATE_PICKUP_APPLICATION_END:
                            if (mDateApplicationStart != null && mCalendar.getTime().before(mDateApplicationStart)) {
                                ToastUtils.show(getApplicationContext(), getString(R.string.active_release_date_error));
                                return;
                            }
                            mDateApplicationEnd = mCalendar.getTime();
                            break;
                        case FLAG_DATE_PICKUP_ACTIVE_START:
                            if (mDateApplicationEnd != null && mCalendar.getTime().before(mDateApplicationEnd)) {
                                ToastUtils.show(getApplicationContext(), getString(R.string.active_release_date_error_application_end));
                                return;
                            } else if (mDateActiveEnd != null && mCalendar.getTime().after(mDateActiveEnd)) {
                                ToastUtils.show(getApplicationContext(), getString(R.string.active_release_date_error));
                                return;
                            }
                            mDateActiveStart = mCalendar.getTime();
                            break;
                        case FLAG_DATE_PICKUP_ACTIVE_END:
                            if (mDateActiveStart != null && mCalendar.getTime().before(mDateActiveStart)) {
                                ToastUtils.show(getApplicationContext(), getString(R.string.active_release_date_error));
                                return;
                            }
                            mDateActiveEnd = mCalendar.getTime();
                            break;
                    }

                    // update UI
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                    tv.setText(df.format(mCalendar.getTime()));
                }
            }
        }, year, month, day);
        Window dialogWindow = datePickerDialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = dm.widthPixels;
        p.height = (int) (dm.heightPixels * 0.3);
        dialogWindow.setAttributes(p);
        datePickerDialog.show();
    }


    private void releaseActive() {
        // check data if null
        if (TextUtils.isEmpty(activeName.getText().toString()) ||

                TextUtils.isEmpty(signStart.getText().toString()) ||
                TextUtils.isEmpty(signEnd.getText().toString()) ||
                TextUtils.isEmpty(timeStart.getText().toString()) ||
                TextUtils.isEmpty(timeEnd.getText().toString()) ||
                TextUtils.isEmpty(activeContent.getText().toString()) ||

                TextUtils.isEmpty(activeName.getText().toString()) ||
                TextUtils.isEmpty(activeStartAddress.getText().toString()) ||
                TextUtils.isEmpty(activeEndAddress.getText().toString()) ||
                TextUtils.isEmpty(activeMemberMax.getText().toString()) ||
                mStartLoc == null ||
                mEndLoc == null ||

                !mActivePicSet) {
            ToastUtils.show(this, getString(R.string.active_release_date_empty));
            return;
        }

        // end of check data
        final MaterialDialog uploadDialog = new MaterialDialog.
                Builder(this).
                content("正在发布...").
                progress(true, 5000).
                build();
        uploadDialog.show();
        TypedFile avatar;
        File headImageFile = activeImgSaveToLocal();
        avatar = (headImageFile.equals("")) ? null : new TypedFile("image/jpg", headImageFile);
        ReleaseActiveParams params = new ReleaseActiveParams();
        params.userId = String.valueOf(PersistUtils.getUsers().get(0).getAccountId());
        params.title = activeName.getText().toString();
        params.source = "0"; // 个人
        params.maxMemberCount = Integer.valueOf(activeMemberMax.getText().toString());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        params.campaign_start_time = simpleDateFormat.format(mDateActiveStart.getTime());
        params.campaign_end_time = simpleDateFormat.format(mDateActiveEnd.getTime());
        params.register_start_time = simpleDateFormat.format(mDateApplicationStart.getTime());
        params.register_end_time = simpleDateFormat.format(mDateApplicationEnd.getTime());
        params.content = activeContent.getText().toString();
        params.deptLng = mStartLoc.longitude;
        params.deptLat = mStartLoc.latitude;
        params.deptAddr = activeStartAddress.getText().toString();
        params.arriLng = mEndLoc.longitude;
        params.arriLat = mEndLoc.latitude;
        params.arriAddr = activeEndAddress.getText().toString();
        String reqStr = RestClient.getGson().toJson(params);
        TypedString typedString = new TypedString(reqStr);
        RestClient.getRestService().releaseActive(typedString, avatar, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                if (response.getStatus() == 200 && restResponse.mErrorCode.equals("0")) {
                    Gson gson = JsonUtils.getGson();
                    String s = gson.toJson(restResponse.mData);
                    uploadDialog.dismiss();

                } else {
                    uploadDialog.dismiss();
                }
                EventBus.getDefault().post(new ReleaseActiveEvent());
                finish();
//            finishActivity(MySettings.UPDATE_PROFILE);
            }

            @Override
            public void failure(RetrofitError error) {
                uploadDialog.dismiss();
            }
        });


    }

    private void showCropWindow(File imageFile) {
        PopupWindow popupWindow = new PopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.window_image_cropper, null);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setContentView(view);
        popupWindow.showAtLocation(popParent, Gravity.BOTTOM, 0, 0);
        popupWindow.update();
        CropImageView cropImageView = (CropImageView) view.findViewById(R.id.cropImageView);
        cropImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        File mFile = new File(imageFile.getAbsolutePath());
        if (mFile.exists()) {//若该文件存在
            Bitmap bm = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
            bm = BitmapUtils.getAdaptiveBitmap(bm);
            cropImageView.setImageBitmap(bm);
        }
        cropImageView.setFixedAspectRatio(true);
        cropImageView.setGuidelines(CropImageView.DEFAULT_GUIDELINES);
        cropImageView.setAspectRatio(5, 2);
        view.findViewById(R.id.crop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取裁剪成的图片
                Bitmap croppedImage = cropImageView.getCroppedImage();
                if (croppedImage != null) {
                    mActivePic.setImageBitmap(croppedImage);
                    mActivePicSet = true;
                }
                popupWindow.dismiss();
            }
        });
    }

    private File activeImgSaveToLocal() {
        String IMAGE_FILE_NAME = "temp_header.jpg";
        File activeImageFile = BitmapUtils.saveBmpFile(((BitmapDrawable) mActivePic.getDrawable()).getBitmap(), IMAGE_FILE_NAME);
        return activeImageFile;
    }
}
